#!/bin/sh
#
# V 1.1 by Thales A. Tsailas (Modified the fedora Startup Scripts to Slackware Needs)
# description: Pound is a reverse proxy, load balancer and HTTPS front-end
# processname: pound
# config: /etc/pound/pound.cfg
# pidfile: /var/run/pound_pid.nnn

if [ -f /var/run/pound.pid ]; then
  pid=`cat /var/run/pound.pid`
else
  pid=-1;
fi

. /etc/init.d/functions

# This is our service name
BASENAME=pound
if [ -L $0 ]; then
  BASENAME=`find $0 -name $BASENAME -printf %l`
  BASENAME=`basename $BASENAME`
fi

[ -f /etc/pound/pound.cfg ] || exit 1

ROOTJAIL=$(grep -si "^RootJail" /etc/${BASENAME}/${BASENAME}.cfg | cut -d " " -f 2)
[ "$ROOTJAIL" = "/" ] && ROOTJAIL=""

RETVAL=0

start() {
  echo -n $"Starting $BASENAME: "
  if [ -n "$ROOTJAIL" ]; then
    [ -d $ROOTJAIL/dev ] || mkdir -p $ROOTJAIL/dev
    mount --bind /dev $ROOTJAIL/dev
  fi
  /usr/sbin/$BASENAME
  RETVAL=$?
  echo
  [ $RETVAL -eq 0 ] 
  return $RETVAL
}

stop() {
  echo -n $"Shutting down $BASENAME: "
  (cat /var/run/pound*pid* | \
    while read pid; do kill $pid; done) 2> /dev/null
    rm -f /var/run/pound*pid*
    if [ -n "$ROOTJAIL" ]; then
      mount | awk '{ if ($6 ~ /bind/ ) print $3}' | grep "^$ROOTJAIL/dev" | while read i; do
        umount $ROOTJAIL/dev 2> /dev/null
      done
    fi
  usleep 100000
  ! pidof -s $BASENAME > /dev/null
  RETVAL=$?
  [ $RETVAL -eq 0 ] && success
  [ $RETVAL -ne 0 ] && failure
  echo
  [ $RETVAL -eq 0 ] && rm -f /var/run/pound_pid.*
  return $RETVAL
}

restart() {
  stop
  start
}


condrestart() {
  [ -e /var/lock/subsys/$BASENAME ] && restart || :
}

# See how we were called.
case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    restart
    ;;
  reload)
    restart
    ;;
  condrestart)
    condrestart
    ;;
  status)
    if [ -f /var/run/pound.pid ]; then
           echo -en "pound is running with pid : $pid \n";
    else
           echo -en "pound is not running\n";
    fi
    ;;
  *)
    echo $"Usage: $BASENAME {start|stop|restart|reload|condrestart|status}"
    RETVAL=1

esac
exit $RETVAL
